package me.qi.kancha.security.grant.custom;

import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

/**
 * 自定义授权模式
 *
 * @author sun
 * @date 2019/9/25 9:34
 */
public class CustomTokenGranter extends AbstractTokenGranter {

    private CustomAuthService customAuthService;

    public CustomTokenGranter(AuthorizationServerTokenServices tokenServices,
                              ClientDetailsService clientDetailsService,
                              OAuth2RequestFactory requestFactory,
                              CustomAuthService customAuthService) {
        super(tokenServices, clientDetailsService, requestFactory, customAuthService.getGrantType());
        this.customAuthService = customAuthService;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        Authentication userAuthentication = customAuthService.authorization(storedOAuth2Request);
        if (userAuthentication == null || !userAuthentication.isAuthenticated()) {
            throw new InvalidGrantException(customAuthService.getGrantType() + "认证失败");
        }
        return new OAuth2Authentication(storedOAuth2Request, userAuthentication);
    }
}
